#include"io.h"
IO_FILE* myopen(const std::string filename,const std::string mode){
    int fd=-1;
    if(mode=="r"){
        fd=open(filename.c_str(), O_RDONLY);
    }
    else if(mode=="w"){
        fd=open(filename.c_str(), O_CREAT|O_WRONLY|O_TRUNC, 0666);
    }
    else if(mode=="a"){
        open(filename.c_str(), O_CREAT|O_WRONLY|O_APPEND, 0666);
    }
    if(fd==-1){
        return nullptr;
    }
    IO_FILE* nf=new IO_FILE;
    if(nf==nullptr){
        perror("new");
        return nullptr;
    }
   nf->flag=FLUSH_LINE;
    nf->size=0;
    nf->fileno=fd;
    return nf;
}
int myfflush(IO_FILE* filename){
    write(filename->fileno,filename->outbuffer.c_str(),filename->size);
    filename->size=0;
    fsync(filename->fileno);
    return 0;
}
int mywrite(const char* ptr,int sz,IO_FILE* filename){
    int len=strlen(ptr),outbuffer_sz=filename->size;
    if(sz+outbuffer_sz>=MX){
        myfflush(filename);
        std::cout<<"ww";
    }
    //std::cout<<outbuffer_sz<<' '<<sz<<std::endl;
    for(int i=0;i<sz;i++){
        filename->outbuffer[i+outbuffer_sz]=ptr[i];
    }
    //std::cout<<ptr<<std::endl;
    //std::cout<<filename->outbuffer;
    filename->size+=sz;
    if(filename->fileno== FLUSH_LINE && filename->size>0){
        myfflush(filename);
    }
    return 0;
}
int myclose(IO_FILE* filename){
    if(filename->size>0){
        myfflush(filename);
    }
    close(filename->fileno);
    return 0;
}
